<?php
namespace app\index\controller;
use EasyWeChat\Factory;
use app\index\model;
vendor('timSdk/TimRestApi');
header("Access-Control-Allow-Origin:*");
header('Access-Control-Allow-Headers:x-requested-with,content-type');
class Login extends \think\Controller {

    public $app;
    public $userinfo;
    public $uid;
    
    public $userModel;
    public $questionModel;
    public $roomquestionModel;
    
    public $roomModel;
    public $roomuserModel;

    public $timCtl;

    public function __construct() {
        parent::__construct();
        $this->userModel = new model\User;
        $this->roomquestionModel = new model\RoomQuestion;
        $this->questionModel = new model\Question;
        $this->roomModel = new model\Room;
        $this->roomuserModel = new model\RoomUser;
        $this->_setConfig();
        $config = [
            'app_id' => config('appid'),
            'secret' => config('appsecret'),
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
//            'log' => [
//                'level' => 'debug',
//                'file' => __DIR__ . '/wechat.log',
//            ],
            'oauth' => [
                'scopes' => ['snsapi_userinfo'],
                'callback' => '/index/index/oauth_callback',
            ],
        ];
        $this->app = Factory::officialAccount($config);
        
       
    }
    
    protected function _setConfig () {
        $list = db('config')->select()->toArray();
        foreach ($list as $v) {
            config($v['key'], $v['value']);
        }
    }
    
    public function index () {
        addlog();
        $data = input();
        $info = $data['userInfo'];
        if(empty($info)) {
            return ajaxReturn(1, 'error');
        }
        
        $userinfo = [
            'openid' => $info['openid'],
            'nickname' => $info['nickname'],
            'headimgurl' => $info['headimgurl'],
            'unionid' => $info['unionid'],
        ];
        $old = $this->userModel->getOne(['unionid'=>$userinfo['unionid']]);
        if(!$old) {
            $userinfo['create_time'] = getDateTime();
            //$userinfo['uniid'] = md5(uniqid().time().rand(10000,99999));
            $uid = $this->userModel->insertGetId($userinfo);
            $this->userModel->where('uid',$uid)->update(['uniid'=>'tim'.$uid]);
        }else{
            $uid = $old['uid'];
        }
        getUserSign($uid);
        _login($uid);
        return ajaxReturn(0, 'ok', $userinfo);
    }

}
